package com.kingsalert.kingsalert.base;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.webkit.WebView;

import com.kingsalert.kingsalert.analytics.data_sdk.ASBuilder;
import com.kingsalert.kingsalert.analytics.data_sdk.ASSycManager;
import com.kingsalert.kingsalert.util.DecUtil;
import com.kingsalert.kingsalert.util.UserInfoUtil;

import org.jetbrains.annotations.NotNull;


public class BaseApplication extends Application {

    private static BaseApplication BaseApplication;

    private String msg;

    @NotNull
    public static BaseApplication getInstant() {
        return BaseApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        BaseApplication = this;
        try {
            //pie webview 适配
            initPieWebView();

            //user info
            UserInfoUtil.getInstance().init(getApplicationContext());

            //syc data sdk
            initSycDataSDK();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 适配android 9 网络进程
     */
    private void initPieWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName(this);
            if (!DecUtil.getPackageName().equals(processName)) {
                WebView.setDataDirectorySuffix(processName);
            }
        }
    }

    private String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (manager != null) {
            for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
                if (processInfo.pid == android.os.Process.myPid()) {
                    return processInfo.processName;
                }
            }
        }
        return "";
    }

    public void initSycDataSDK() {
        try {

            ASBuilder.setLog(false);

            // 初始化
            ASSycManager.getInstance().init(this);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        if (msg == null) return "";
        final String fMSg = msg;
        msg = "";
        return fMSg;
    }

}
